import prisma from "../prisma/index.js";

// 分页查询题库
export async function getQuestions({ type, keyword, pagenum, pagesize }) {
  const where = {};
  if (type) where.type = type;
  if (keyword) where.title = { contains: keyword };
  const skip = (pagenum - 1) * pagesize;
  const [list, total] = await Promise.all([
    prisma.question.findMany({
      where,
      skip,
      take: pagesize,
      orderBy: { id: "desc" },
    }),
    prisma.question.count({ where }),
  ]);
  return {
    list: list.map(q => ({
      ...q,
      options: q.options ? JSON.parse(q.options) : [],
    })),
    total,
  };
}

// 新建题目
export async function createQuestion(data) {
  return prisma.question.create({ data });
}

// 编辑题目
export async function updateQuestion(id, data) {
  return prisma.question.update({ where: { id: Number(id) }, data });
}

// 删除题目
export async function deleteQuestion(id) {
  return prisma.question.delete({ where: { id: Number(id) } });
}

// 批量删除
export async function batchDeleteQuestions(ids) {
  return prisma.question.deleteMany({ where: { id: { in: ids } } });
}